package com.jy.datapipeline.importserver.service.impl;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.fastjson.JSONObject;
import com.jy.datapipeline.common.config.DBMetaDataConfig;
import com.jy.datapipeline.export.controller.MetaDataController;
import com.jy.datapipeline.export.service.DataSourceInfoService;
import com.jy.datapipeline.importserver.common.dto.ImportDataSourceNamesDto;
import com.jy.datapipeline.importserver.service.ImportDataSourceService;
import org.springframework.stereotype.Service;

import java.sql.SQLException;
import java.util.List;
import java.util.Map;

/**
 * @类名 ImportDataSourceServiceImpl
 * @描述 TODO
 * @作者 白条君
 * @创建日期 2023/4/19 15:35
 * @版本 1.0
 */
@Service
public class ImportDataSourceServiceImpl implements ImportDataSourceService {

    private final DataSourceInfoService dataSourceInfoService;

    private final MetaDataController metaDataController;

    public ImportDataSourceServiceImpl(DataSourceInfoService dataSourceInfoService, MetaDataController metaDataController) {
        this.dataSourceInfoService = dataSourceInfoService;
        this.metaDataController = metaDataController;
    }

    @Override
    public List<ImportDataSourceNamesDto> queryDataSourceNames() {
        List<Map<String, Object>> dataSourceInfos = dataSourceInfoService.findDataSourceInfoByList(null, -1, -1);
        return JSONObject.parseArray(JSONObject.toJSONString(dataSourceInfos), ImportDataSourceNamesDto.class);
    }

    @Override
    public List<String> queryDataSourceSchemas(String dataSourceId) throws SQLException {
        return metaDataController.getAllSchemas(DBMetaDataConfig.dataSourceMap.get(dataSourceId));
    }

    @Override
    public List<Map<String, Object>> queryDataSourceColumns(String dataSourceId, String schema, String tableName) throws SQLException {
        DruidDataSource ds = DBMetaDataConfig.dataSourceMap.get(dataSourceId);
        return metaDataController.getTableByColumn(ds, tableName, schema);
    }

    @Override
    public Map<String, Object> queryTables(String dataSourceId, String schema, String searchType, String tblName, Integer endIndex, Map<String, Object> map) throws SQLException {
        return dataSourceInfoService.findTables(dataSourceId, schema, tblName, Integer.parseInt(searchType), 0, endIndex, map);
    }
}
